package com.example.common.domain.pojo.TypeHandler;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.util.List;

/**
 * JSON 与 List 对象互相转换的 TypeHandler
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListJsonTypeHandler extends AbstractJsonTypeHandler<List<Object>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected List<Object> parse(String json) {
        try {
            if (json == null || json.trim().isEmpty()) {
                return null;
            }
            return objectMapper.readValue(json, List.class);
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败: " + json, e);
        }
    }

    @Override
    protected String toJson(List<Object> obj) {
        try {
            if (obj == null) {
                return null;
            }
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("转换对象为JSON失败", e);
        }
    }
}
